package org.tp8.sampleapp.view;

import java.util.Collection;
import java.util.LinkedList;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

import org.tp8.sampleapp.exc.SampleAppException;
import org.tp8.sampleapp.model.Teacher;
import org.tp8.sampleapp.util.SampleAppLogger;

/**
 * The Class TeacherEntityBean.
 */
@ManagedBean(name = "teacherEntityBean")
@RequestScoped
public class TeacherEntityBean extends AbstractEntityBean<Teacher> {

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = -8593178464097873268L;
	/**
	 * The Constant log.
	 */
	private final static SampleAppLogger log = new SampleAppLogger(
			TeacherEntityBean.class);

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.tp8.sampleapp.view.AbstractEntityBean#createNew()
	 */
	@Override
	protected Teacher createNew() {
		return new Teacher();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.tp8.sampleapp.view.AbstractEntityBean#findOne(java.lang.Long)
	 */
	@Override
	protected Teacher findOne(Long id) {
		Teacher teacher;
		try {
			teacher = getTeacherFacade().findOne(id);
		} catch (SampleAppException e) {
			log.error(e);
			teacher = null;
		}
		return teacher;
	}

	/**
	 * Save.
	 * 
	 * @param teacher
	 *            the teacher
	 */
	public void save(Teacher teacher) {
		FacesMessage message;
		FacesContext context = FacesContext.getCurrentInstance();
		try {
			setItem(getTeacherFacade().save(teacher));
			message = new FacesMessage("Successfully saved");
		} catch (SampleAppException e) {
			message = new FacesMessage(FacesMessage.SEVERITY_ERROR,
					"There was an error during saving.", e.getMessage());
		}

		context.addMessage(null, message);
	}

	/**
	 * Delete.
	 * 
	 * @param id
	 *            the id
	 */
	public void delete(Long id) {
		FacesMessage message;
		FacesContext context = FacesContext.getCurrentInstance();
		try {
			getTeacherFacade().delete(id);
			message = new FacesMessage("Successfully deleted");
		} catch (SampleAppException e) {
			message = new FacesMessage(FacesMessage.SEVERITY_ERROR,
					"There was an error during deletion.", e.getMessage());
		}

		context.addMessage(null, message);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.tp8.sampleapp.view.AbstractEntityBean#findAll()
	 */
	@Override
	public Collection<Teacher> findAll() {
		Collection<Teacher> list;
		try {
			list = getTeacherFacade().findAll();
		} catch (SampleAppException e) {
			log.error(e);
			list = new LinkedList<>();
		}
		return list;
	}

}
